from django.shortcuts import HttpResponse,render,redirect
from django.core.exceptions import ValidationError

from app01 import models
from app01.utils.encrypt import md5


from app01.utils.pagination import Pagination
from app01.utils.bootstrapmodel import BootStrapModelForm
def adminuser_list(request):
    '''管理员列表'''
    #搜索的功能
    #检查用户是否登录，如果已经登录，继续往下走，如果未登录，跳转回登录页面
    #用户发送请求，获取cookie随机字符创，拿着随机字符串看卡session中有没有
    info=request.session.get('info')
    print(info)
    info_dic=request.session['info']
    print(info_dic['id'])
    print(info_dic['name'])
    if not info:
        return redirect('/login/')
    data_dic={}
    search_data=request.GET.get('q','')
    if search_data:
        data_dic={
            'username__contains':search_data
        }
    #根据搜索条件去数据库获取
    queryset=models.Adminuser.objects.filter(**data_dic)
    #分页的功能
    page_object=Pagination(request,queryset)
    context={
        'queryset':page_object.page_queryset,
        'search_data':search_data,
        'page_string':page_object.html()
    }
    return render(request,'admin_list.html',context)
from django import forms
class AdminuserModelForm(BootStrapModelForm):
    confirm_password=forms.CharField(
        label="确认密码",
        # widget=forms.PasswordInput(attrs={'class': 'form-control'})
        widget=forms.PasswordInput(render_value=True)#render_value写为True那么网页上不清空
    )
    class Meta:
        model=models.Adminuser
        fields=['username','password','confirm_password']
        # fields=['username','password']
        widgets={
            # 'password':forms.PasswordInput(attrs={'class': 'form-control'})
            'password':forms.PasswordInput(render_value=True)#render_value写为True那么网页上不清空
        }

    def clean_password(self):
        pwd=self.cleaned_data.get("password")
        return md5(pwd)
    def clean_confirm_password(self):
        # print(self.cleaned_data)
        # print(self.cleaned_data.get)
        pwd=self.cleaned_data.get('password')
        confirm=md5(self.cleaned_data.get("confirm_password"))
        if confirm!=pwd:
            raise ValidationError("密码不一致")
        return confirm#return什么，此字段保存到数据库就是什么

class AdminuserEditModelForm(BootStrapModelForm):

    class Meta:
        model=models.Adminuser
        fields=['username']

class AdminuserResetModelForm(BootStrapModelForm):
    confirm_password = forms.CharField(
        label="确认密码",
        # widget=forms.PasswordInput(attrs={'class': 'form-control'})
        widget=forms.PasswordInput(render_value=True)  # render_value写为True那么网页上不清空
    )
    class Meta:
        model=models.Adminuser
        fields=['password']
        widgets={
                    # 'password':forms.PasswordInput(attrs={'class': 'form-control'})
                    'password':forms.PasswordInput(render_value=True)#render_value写为True那么网页上不清空
                }

    def clean_password(self):
        pwd=self.cleaned_data.get("password")
        md5_pwd=md5(pwd)
        #去数据库校验一下当前密码和新输入的密码是否一致
        # self.instance.pk
        exists=models.Adminuser.objects.filter(id=self.instance.pk,password=md5_pwd).exists()
        if exists:
            raise ValidationError('密码与原始密码一样')
        return md5(pwd)
    def clean_confirm_password(self):
        # print(self.cleaned_data)
        # print(self.cleaned_data.get)
        pwd=self.cleaned_data.get('password')
        confirm=md5(self.cleaned_data.get("confirm_password"))
        if confirm!=pwd:
            raise ValidationError("密码不一致")
        return confirm#return什么，此字段保存到数据库就是什么

def adminuser_add(request):
    '''添加管理员'''
    title="新建管理员"
    if request.method=='GET':
        form=AdminuserModelForm()
        return render(request,'change.html',{'form':form,'title':title})
    # form=AdminModelForm(data=request.POST)
    form = AdminuserModelForm(data=request.POST)
    # print('*'*90)
    # print(form)
    if form.is_valid():  # 将数据逐一进行检查是否为空
        # print(form.cleaned_data)
        form.save()
        return redirect('/admin/list/')
    return render(request, 'change.html', {'form': form, 'title':title})
def adminuser_edit(request,nid):
    '''编辑管理员'''
    #对象、None
    row_obj=models.Adminuser.objects.filter(id=nid).first()
    # print(f'row obj is{row_obj}')
    if not row_obj:
        #return 错误页面
        return render(request,'error.html',{'msg':"数据不存在!"})
        return redirect('/admin/list/')
    title="编辑管理员"
    if request.method=='GET':
        form=AdminuserEditModelForm(instance=row_obj)
        return render(request, 'change.html', {'form':form, 'title': title,'nid':nid})
    form=AdminuserEditModelForm(data=request.POST,instance=row_obj)
    if form.is_valid():  # 将数据逐一进行检查是否为空
        # print(form.cleaned_data)
        form.save()
        return redirect('/admin/list/')
    return render(request, 'change.html', {'form': form, 'title':title})

def adminuser_del(request,nid):
    '''删除管理员'''
    #对象、None
    models.Adminuser.objects.filter(id=nid).first().delete()
    return redirect('/admin/list/')

def adminuser_reset(request,nid):
    """重置密码"""
    row_obj = models.Adminuser.objects.filter(id=nid).first()
    # print(f'row obj is{row_obj}')
    if not row_obj:
        return redirect('/admin/list/')
    title = "密码重置-{}".format(row_obj.username)
    if request.method=='GET':
        form=AdminuserResetModelForm()
        return render(request, 'change.html', {'form':form,'title': title})
    form = AdminuserResetModelForm(data=request.POST,instance=row_obj)
    if form.is_valid():
        form.save()
        return redirect('/admin/list/')
    return render(request, 'change.html', {'form': form, 'title': title})
